import express from 'express'
import { getToken } from '../../auth/auth.js'
import * as userServer from "../../controllers/user.js"

const router = express.Router();

// 1.用户登录接口
router.post("/", async (req, res, next) => {
    try {
        console.log('开始处理 /admin/login 请求...');
        const { username, password } = req.body;
        
        if (!username || !password) {
            return res.status(400).send({
                code: 400,
                msg: "用户名和密码不能为空"
            });
        }

        let [user] = await userServer.selectUserByUsernameAndPassword(username, password);

        if (user == null) {
            return res.status(401).send({
                code: 401,
                msg: "用户名或密码错误"
            });
        }
        res.send({
            code: 200,
            msg: "登录成功",
            token: "Bearer " + getToken(user)
        });
    } catch (error) {
        console.error('用户登录失败:', error);
        res.status(500).send({
            code: 500,
            msg: "登录失败"
        });
    }
});

export default router;